﻿package net.wangit.view.element.component;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.support.AbstractElementWriter;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.element.util.ElementUtil;
import net.wangit.view.enumeration.EnumerationUtil;
import net.wangit.view.util.Html;

public class CheckBoxSetFieldElementWriter extends AbstractElementWriter {

	public CheckBoxSetFieldElementWriter() {
	}

	protected void writeText(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		MapList enumeration = (MapList) ec.getObject();
		String value = ElementUtil.getValueOrDefault(ac, ec, row);
		String values[] = StringUtil.split(value, ",");
		Html
				.set(html, EnumerationUtil.getEnumerationNames(enumeration,
						values));
	}

	protected void writeTextWithValue(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeText(ac, html, ec, row);
		ElementUtil.setHidden(ac, html, ec, row);
	}

	protected void writeControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		String value = ElementUtil.getValueOrDefault(ac, ec, row);
		html.append(
				"<span onclick=\"$f53(this)\"><input type=\"hidden\" name=\"")
				.append(ElementUtil.getAlias(ec)).append("\"");
		Html.setValue(html, value);
		html.append("/>");
		writeOptions(ac, html, ec, row, false);
		html.append("</span>");
	}

	protected void writeReadOnlyControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeDisabledControl(ac, html, ec, row);
		ElementUtil.setHidden(ac, html, ec, row);
	}

	protected void writeDisabledControl(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		writeOptions(ac, html, ec, row, true);
	}

	protected void writeHidden(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row) {
		ElementUtil.setHidden(ac, html, ec, row);
	}

	private void writeOptions(ActionContext ac, StringBuffer html,
			ElementComponent ec, Row row, boolean disabled) {
		MapList enumeration = (MapList) ec.getObject();
		if (!Checker.isEmpty(enumeration)) {
			String values[] = StringUtil.split(ElementUtil.getValueOrDefault(
					ac, ec, row), ",");
			for (int i = 0; i < enumeration.size(); i++) {
				Row item = enumeration.getRow(i);
				String itemValue = item.get("value");
				String itemName = item.get("name");
				String custom = item.get("custom");
				html.append("<input type=\"checkbox\"");
				if (disabled)
					html.append(" disabled");
				Html.setAttribute(html, custom);
				Html.setAttribute(html, ElementUtil.resolveCustom(ac, ec, row));
				Html.setValue(html, itemValue);
				Html.setChecked(html, values, itemValue);
				Html.setCss(html, ec.getCss(), "E7");
				html.append("/>").append(itemName);
			}

		}
	}
}
